<template>
  <el-card class="card-books">
    <div class="head">
      <span class="tip">
        图书种类：
      </span>
      <span class="category">
        <el-dropdown>
          <el-button type="primary">
            {{ categoryBtn }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="category in categories" :key="category" :command="category" @click="selectCategory(category)">
              {{ category }}
            </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" class="returnButton" v-if="admin === '2'" @click="booksBack">图书归还</el-button>
        <el-button type="primary" class="returnButton" v-if="admin === '2'" @click="booksGet">图书获取</el-button>
        <el-card title="上传图片" v-if="this.dialogVisible === true" class="cardToBack">
          <el-upload class="upload-demo" drag multiple @change="handleFileUpload">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              Drop file here or <em>click to upload</em>
            </div>
          </el-upload>
          <div v-if="isReturn === true">
            <el-text style="margin-left: 20px;display: flex;">图书归还情况：</el-text>
            <el-radio-group v-model="radio1" class="ml-4" direction="vertical">
              <el-radio value="1" size="large" >图书损毁严重</el-radio>
              <el-radio value="2" size="large" >图书丢失</el-radio>
              <el-radio value="3" size="large" >图书正常归还</el-radio>
            </el-radio-group>
          </div>
          
          <div style="display: flex;margin-left: 100px;margin-top: 50px;">
            <el-button @click="close=>{this.dialogVisible = 0}" type="primary">取消</el-button>
            <el-button @click="submitImage" type="primary" style="margin-left: 30px;">提交</el-button>
          </div>
          
        </el-card>
      </span>
      <span class="search">
        <el-form :inline="true" :model="formInline" class="search">
        <el-form-item>
          <el-input v-model="search" placeholder="搜索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      </span>
    </div>
    <div class="middle">
      <div>
        <el-table :data="books" :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }" border header-align="center" align="center">
        <el-table-column fixed prop="bookId" label="书号" width="100"  ></el-table-column>
        <el-table-column fixed prop="bookName" label="书名" width="300"></el-table-column>
        <el-table-column fixed prop="author" label="作者" width="250" ></el-table-column>
        <el-table-column fixed prop="ISBN" label="ISBN" width="200" ></el-table-column>
        <el-table-column fixed prop="quantity" label="数量" width="70"></el-table-column>
        <el-table-column fixed label="操作" width="230">
          <template v-slot="{row}">
            <el-button plain @click="checkBook(row)" type="info">详情</el-button>
            <el-button plain @click="borrowMsg(row)">借阅</el-button>
            <el-button plain v-if="admin === '2'" @click="deleteBook(row.bookId)" type="danger">删除</el-button>
        </template>
        </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="bottom" >
      <el-pagination background layout="prev, pager, next" :total="1000" :page-count="pageNumber" class="pagination" @current-change="handleCurrentChange"/>
    </div>
  </el-card>
</template>

<script>
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
// 导入 qrcode-reader 库
import jsQR from 'jsqr'; // 导入jsQR库

export default {
    name: 'Books',
    data() {
      return {
        search:'',
        categoryBtn:'全部',
        selectedCategory: '全部', // 用于存储选中的城市
        categories: [], // 城市数组'计算机科学', '历史', '小说','文学','科幻','外语'
        books: [],
        qrCodeData: '',
        pageNumber: '',
        username:localStorage.getItem('username'),
        admin: localStorage.getItem('admin'),
        dialogVisible: false,
        radio1 : ref('1'),
        isReturn: '',
        base64String:''
      }
    },
    methods: {
      //图书归还
      booksBack(){
        this.isReturn = true
        this.dialogVisible = !this.dialogVisible;
        console.log(this.dialogVisible)
      },
      booksGet(){
        this.isReturn = false
        this.dialogVisible = !this.dialogVisible
      },
      handleUploadSuccess(response, file) {
        // 处理图片上传成功后的逻辑
        console.log('上传成功', response, file);
      },
      submitImage() {
        // 提交图片的逻辑
        console.log('提交图片');
        ElMessage({
          message: '提交成功！',
          type: 'success',
        })

        // 可以在这里编写提交图片的逻辑
        this.returnBook(this.base64String)
        this.dialogVisible = false;
      },

        handleCurrentChange(page) {
          // 在这里处理分页逻辑，例如获取对应页码的数据
          console.log('当前页码:', page)
          this.getBooks(this.selectedCategory , page)
          // 可以在这里调用获取数据的方法或更新页面内容
        },
        async generateQRCode() {
        try {
            const qrData = 'iVBORw0KGgoAAAANSUhEUgAAASIAAAEiAQAAAAB1xeIbAAABb0lEQVR4nO2aQW7DIBBF/5RIXuIb5Cj4ZlWP1BvAUXIDs4xE9LsA3GTVbgyOmVlZ6EnzNYzNZ2Qh/o7w8Q8IUEoppZRS6uiUlLgAiBfIEuvK0lXXEJQjSa4AwjWBHoYkyVeqva4hqFh6XD5v9Sm/Bp11DUWFuXVGpbawqXXGUan6WbEEEAG474kCAM+XrqOqf2+q1D4IAMBs6w/ZK6NSNXLtn3o8XO9SXoOeusahqqG/gLxNzLZHfU4jypKATRC5JgA2Idv93rrOTCHfobgCcGtd85aEW8sFi/6o6t+bqrVnQm7+UvGUt0JrvzslIhPpowi9vQvCbAjAUJauus5NbX3PlwEODOmhfd+A+p1j5g1wa/H3snTVdW6qFjsfuIZ1pmDy+at934CK26w+ToTjXQAYnSE3pRx1ltaLCvND+DVvFmf/jMNTlsXY+DhtZ+02UDu6+remgoiIzIAseDz5+966Tk2J/hullFJKKTUE9QMXVcKxgMR7bgAAAABJRU5ErkJggg==';
            const qrDataURL = await QRCode.toDataURL(qrData);
            this.qrCodeData = qrDataURL;
        } catch (error) {
            console.error('Error generating QR Code:', error);
        }
        },
      //使用结构赋值进行异常处理
			promise_error_process(promise){
				return promise.then(data=>[null,data])
								.catch(err=>[err,null])
			},
      onSubmit() {
        console.log('submit!')
        if(this.search === ''){
          this.getBooks(this.categoryBtn,1)
          this.getPageNumber(this.categoryName,1)
        }else{
          this.searchBook(this.search , 1)

        }
        
      },
      checkBook(row) {
        console.log('查看', row)
        this.$router.push({name: 'BookInfo' , query:{bookId:row.bookId}})
      },
      borrow(row){
        
        console.log('borrow!' , row)

      },

      //获取图书列表（按页数）
      async getBooksByAjax(categoryName,page){
        const response = await axios({
					url 			: `http://127.0.0.1:8080/api/books/bookList/${categoryName}/${page}`,
					method  		: 'GET',
					withCredentials : true
				})
				return response;
      },
      async getBooks(categoryName,page){
        const [err,result] = await this.promise_error_process(this.getBooksByAjax(categoryName,page))
        if(err){
          console.log(err)
        }
        else{
          console.log(result+ "result")
          this.books = result.data.data.books

        }
      },

      //获取页数
      async getPageNumberByAjax(username_c,type){
        const response = await axios({
            url				: `http://127.0.0.1:8080/api/books/pageNumber/${username_c}/${type}`,
            method			: 'GET',
            withCredentials : true
          })
          return response
      },
      async getPageNumber(username_c,type){
        const [err,result] = await this.promise_error_process(this.getPageNumberByAjax(username_c,type))
        if(err)
          console.log('请求异常')
        else{
          console.log(result.data.data)
          this.pageNumber = result.data.data
        }
      },
      async selectCategory(category) {
        this.categoryBtn = category;
        this.selectedCategory = category;
        this.getBooks(this.categoryBtn , 1)
        this.getPageNumber(this.selectedCategory , 1)
        console.log("pageNum="+this.pageNumber)
      },

      //删除图书
      async deleteBookByAjax(bookId){
        const response = await axios({
            url				: `http://127.0.0.1:8080/api/books/deleteBook/${bookId}`,
            method			: 'DELETE',
            withCredentials : true
          })
          return response
      },
      async deleteBook(bookId){
        const [err,result] = await this.promise_error_process(this.deleteBookByAjax(bookId))
        if(err){
          console.log('请求异常')
        }else{
          console.log(result)
          ElMessageBox.confirm('确定要删除本图书吗？', '提示', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            this.books = this.books.filter(item => item.bookId !== bookId);
          })
          
        }
      },

      //按书名搜索图书
      async searchBookByAjax(bookName , page){
        const response = await axios({
          url:       `http://127.0.0.1:8080/api/books/searchByBookName/${bookName}/${page}`,
          method:    'GET',
          withCredentials:  true
        })
        return response
      },
      async searchBook(bookName , page){
        const [err ,result] = await this.promise_error_process(this.searchBookByAjax(bookName , page))
        if(err)
          console.log("请求异常")
        else{
          console.log(result)
          this.books = result.data.data.books
          this.pageNumber = this.getPageNumber(bookName , 2)
        }
        
      },

      //获取图书种类
      async getCategoryByAjax(){
        const response = await axios({
          url:      `http://127.0.0.1:8080/api/books/category`,
          method:   'GET',
          withCredentials: true,
        })
        return response
      },
      async getCategory(){
        const [err, result] = await this.promise_error_process(this.getCategoryByAjax())
        if(err){
          console.log("请求失败")
        }
        else{
          console.log(result)
          console.log(result.data.data.categoryNames.length)
          this.categories.push('全部')
          for(let i = 0 ; i < result.data.data.categoryNames.length; i++){
            //向categories添加数组中的元素
            this.categories.push(result.data.data.categoryNames[i])
          }
        }

      },
      async borrowMsg(row){
        console.log(row.bookId)
        const [err,result] = await this.promise_error_process(this.borrowBookByAjax(row.bookId))
        if(err){
          console.log(err)
        }
        else{
          console.log(result)
          ElMessageBox.confirm('借阅已成功，您可以到我的借阅中查看借阅的详细信息', '借阅成功', {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'success' // 设置对话框类型为成功
        }).then(() => {
          ElMessage({
            type: 'success',
            message: '借阅成功'
          });
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消'
          });
        });
        }
      },
      async borrowBookByAjax(bookId){
        const response = await axios({
          url:      `http://127.0.0.1:8080/api/borrow/${this.username}/${bookId}`,
          method:   'GET',
          withCredentials:  true
        })
        return response
      },
      async returnBookByAjax(code){
        const response = await axios({
          url:      'http://127.0.0.1:8080/api/borrow/admin/returnUserBook',
          method:   'POST',
          withCredentials: true,
          headers			: {
    				'Content-Type'	: 'application/json'
  				},
          data:{
            code : code,
            evaluation : this.radio1
          }
        })
        return response
      },
      async returnBook(code){
        if(this.isReturn ===true)
        {
          const [err,result] = await this.promise_error_process(this.returnBookByAjax(code))
          if(err){
            console.log(err)
          }
          else{
            console.log(result)
          }
        }
        else{
          const [err,result] = await this.promise_error_process(this.getBookByAjax(code))
          if(err){
            console.log(err)
          }
          else{
            console.log(result)
          }
        }
      },
      async getBookByAjax(code){
        const response = await axios({
          url:      'http://127.0.0.1:8080/api/borrow/getBook',
          method:   'POST',
          withCredentials: true,
          headers			: {
    				'Content-Type'	: 'application/json'
  				},
          data:{
            code    : code,
            username: 'j2ee'
          }
        })
        return response
      },
      handleFileUpload(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const image = new Image();
          image.src = e.target.result;

          image.onload = () => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = image.width;
            canvas.height = image.height;
            context.drawImage(image, 0, 0);

            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            const qrCode = jsQR(imageData.data, imageData.width, imageData.height);

            if (qrCode) {
              console.log('QR Code 解析结果:', qrCode.data);
              this.base64String = qrCode.data
              // 在这里处理二维码识别结果
            } else {
              console.log('未能识别二维码');
            }
          };
        };

        reader.readAsDataURL(file.raw);
      }
    },
    created(){
        this.getBooks(this.categoryBtn,1)
        this.getPageNumber('全部',1)
        this.getCategory()
    }
  }
</script>

<style scoped>
.middle{
  text-align: left;
}
.el-pagination{
  justify-content: right;
  margin-right: 80px;
  margin-top: 5px;
  flex: 1;
}
  .head {
    display: flex;
    justify-content: space-between;
  }
  .category {
    flex: 1;
    text-align: left;
  }
  .search {
    flex: 1;
    text-align: right;
  }
  .bottom{
    display: flex;
    justify-content: space-between;
  }
  .tip{
    margin-top: 3px;
  }
  .returnButton{
    margin-left: 30px;  
  }
.cardToBack{
  width: 400px;
  text-align: center;
  height: 400px;
  position: absolute;
  z-index: 888;
}
.ml-4{
  display: flex;
  margin-top:10px;
  margin-bottom: 20px;
}
</style>